package com.zeros.myself.practice_delete.practice3

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View

/**
 * @author zqq on 2019/12/30.
 */
class Sample13GetTextBoundsView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    internal var paint1 = Paint(Paint.ANTI_ALIAS_FLAG)
    internal var paint2 = Paint(Paint.ANTI_ALIAS_FLAG)

    internal var texts = arrayOf("A", "a", "J", "j", "Â", "â")
    internal var yOffsets = intArrayOf(0, 0, 0, 0, 0, 0)

    internal var top = 200
    internal var bottom = 400


    init {
        paint1.style = Paint.Style.STROKE
        paint1.strokeWidth = 20f
        paint1.color = Color.parseColor("#e91e63")

        paint2.textSize = 160f

        val textBounds = Rect()

        //getTextBounds(String text, int start, int end, Rect bounds)
        //获取文字的显示范围。
        //参数里，
        //text 是要测量的文字，
        //start 和 end 分别是文字的起始和结束位 置，
        //bounds 是存储文字显示范围的对象，方法在测算完成之后会把结果写进 bounds。

        // getTextBounds() 和 measureText() 来测量文字的宽 度，
        // 你会发现 measureText() 测出来的宽度总是比 getTextBounds() 大一点 点。
        paint2.getTextBounds(texts[0], 0, texts[0].length, textBounds)
        yOffsets[0] = -(textBounds.top + textBounds.bottom) / 2

        paint2.getTextBounds(texts[1], 0, texts[1].length, textBounds)
        yOffsets[1] = -(textBounds.top + textBounds.bottom) / 2

        paint2.getTextBounds(texts[2], 0, texts[2].length, textBounds)
        yOffsets[2] = -(textBounds.top + textBounds.bottom) / 2

        paint2.getTextBounds(texts[3], 0, texts[3].length, textBounds)
        yOffsets[3] = -(textBounds.top + textBounds.bottom) / 2

        paint2.getTextBounds(texts[4], 0, texts[4].length, textBounds)
        yOffsets[4] = -(textBounds.top + textBounds.bottom) / 2

        paint2.getTextBounds(texts[5], 0, texts[5].length, textBounds)
        yOffsets[5] = -(textBounds.top + textBounds.bottom) / 2
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawRect(50f, top.toFloat(), width - 50f, bottom.toFloat(), paint1)

        var middle = (top + bottom) / 2

        canvas.drawText(texts[0], 100f, (middle + yOffsets[0]).toFloat(), paint2)
        canvas.drawText(texts[1], 200f, (middle + yOffsets[1]).toFloat(), paint2)
        canvas.drawText(texts[2], 300f, (middle + yOffsets[2]).toFloat(), paint2)
        canvas.drawText(texts[3], 400f, (middle + yOffsets[3]).toFloat(), paint2)
        canvas.drawText(texts[4], 500f, (middle + yOffsets[4]).toFloat(), paint2)
        canvas.drawText(texts[5], 600f, (middle + yOffsets[5]).toFloat(), paint2)

    }

}